<script setup>
import { ref } from 'vue'
import { Edit } from '@element-plus/icons-vue'

import { updateUserInfoService } from '@/api/user'

import bus from '@/utils/bus'

const props = defineProps({
    user: {
        type: Object,
        default: () => ({})
    }
})

const isShowUserName = ref(false)
const newUserName = ref(props.user.userName)

const handleUpdateName = async () => {
    if (newUserName.value.length === 0) {
        ElMessage.error('昵称不能为空')
        newUserName.value = props.user.userName
        close()
        return
    }
    await updateUserInfoService({
        username: newUserName.value
    })
    bus.emit('updateInfo')
    close()
}

const close = () => {
    newUserName.value = props.user.userName
    isShowUserName.value = false
}
</script>
<template>
    <div class="personal-info">
        <div class="nickname-div">
            <div class="like">昵称：</div>
            <!-- 昵称展示 -->
            <div v-show="!isShowUserName" class="content">
                <span class="each">{{ user.userName }}</span>
                <span @click="isShowUserName = !isShowUserName" class="edit-btn">
                    <el-icon>
                        <Edit />
                    </el-icon>修改
                </span>
            </div>

            <!-- 昵称编辑 -->
            <div v-show="isShowUserName" class="editing">
                <el-input maxlength="10" placeholder="请输入更新后的昵称" show-word-limit v-model="newUserName" clearable
                    class="editing-input">
                </el-input>
                <el-button @click="handleUpdateName" type="primary" class="editing-btn">保存</el-button>
                <el-button @click="close" class="editing-btn">取消</el-button>
            </div>
        </div>
    </div>
</template>
<style scoped lang="scss">
.personal-info {
    display: flex;
    flex-direction: column;
    justify-content: space-around;

    .nickname-div,
    .gender {
        display: flex;
        align-items: center;
        margin: 1rem 0;
    }
}

.like {
    font-size: 1.3rem;
}

.content {
    display: flex;
    align-items: center;
    font-size: 1.2rem;
}

.edit-btn {
    margin-left: 1rem;
    display: flex;
    align-items: center;
    color: rgb(23, 81, 153);
    white-space: nowrap;
    cursor: pointer; // 鼠标放上去显示手势
}

.editing-input {
    margin-bottom: 0.5rem;
}
</style>
